<template>
  <div class="notfound-border">
    <beetles-search :size="'mini'" :expend="true" @search-form="submitForm" @empty-form="emptyForm" :loading="loading">
      <template slot-scope="{searchConceal, disabled}" slot="searchForm">
        <el-form ref="form" :model="query" :rules="rules" label-width="100px"  @submit.native.prevent>
          <el-row :gutter="20" style="display: flex;flex-wrap: wrap">
            <div v-if="oc !== true">
              <el-form-item label="订单名称: " prop="offerId">
                <el-select size="mini" style="width: 190px" v-model="query.offerId" placeholder="请选择订单" clearable
                           filterable @change="changOffer">
                  <el-option v-for="item in offerList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div>
              <el-form-item prop="name">
                <template v-slot:label>
                  <el-tooltip class="item" effect="dark" content="从广告后台实际获取到的素材名称" placement="top">
                    <span>素材名称:</span>
                  </el-tooltip>
                </template>
                <el-input size="mini" v-model="query.name" clearable placeholder="请输入素材名称" style="width: 190px"
                          @keyup.enter.native="submitForm"></el-input>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="更新时间: " prop="reportDate">
                <el-date-picker
                  style="width: 250px"
                  size="mini"
                  v-model="updateTimeRange"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  ref="performTime" @change="submitForm">
                </el-date-picker>
              </el-form-item>
            </div>
            <div>
              <el-form-item prop="platform">
                <template v-slot:label>
                  <el-tooltip class="item" effect="dark" content="广告/素材实际产生归因数据的平台" placement="top">
                    <span>媒体:</span>
                  </el-tooltip>
                </template>
                <el-select size="mini" style="width: 190px" v-model="query.platform" placeholder="请选择媒体" clearable @change="submitForm">
                  <el-option v-for="item in platformList"
                             :key="item.dictKey"
                             :label="item.dictValue"
                             :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!--              <div>-->
            <!--                <el-form-item label="投放地区: " prop="countryList">-->
            <!--                  <el-select size="mini" style="width: 190px"-->
            <!--                             v-model="query.countryList" collapse-tags multiple clearable filterable placeholder="请选择投放地区"-->
            <!--                             ref="performNation" @change="submitForm">-->
            <!--                    <el-option v-for="(item,index) in nationList"-->
            <!--                               :key="index"-->
            <!--                               :label="item.dictValue"-->
            <!--                               :value="item.dictKey">-->
            <!--                    </el-option>-->
            <!--                  </el-select>-->
            <!--                </el-form-item>-->
            <!--              </div>-->
            <div>
              <el-form-item label="素材类型: " prop="type">
                <el-select size="mini" style="width: 190px" v-model="query.type" clearable filterable
                           placeholder="请选择素材类型"
                           ref="performNation" @change="submitForm">
                  <el-option v-for="(item,index) in typeList" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="AssetId: " prop="assetId">
                <el-input size="mini" v-model="query.assetId" clearable placeholder="请输入AssetId" style="width: 190px"
                          @keyup.enter.native="submitForm"></el-input>
              </el-form-item>
            </div>
          </el-row>
        </el-form>
      </template>
    </beetles-search>

    <basic-container>
      <avue-crud :option="option"
                     :data="data"
                     :table-loading="loading"
                     :page.sync="page"
                     :view-name="'notfoundCreative'"
                     ref="crud"
                     @search-change="searchChange"
                     @search-reset="searchReset"
                     @selection-change="selectionChange"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     @refresh-change="refreshChange"
                     @sort-change="sortChange"
                     @on-load="onLoad"
      >
        <template slot-scope="{ row }" slot="assetUrl">
          <div @click="handleMediaPreview(row)" style="max-height: 100px;height: auto; width: 100%"
               :class="obsStyle(row)">
            <el-image
              fit="contain"
              v-if="getMediaType(row) == 'image'"
              style="width: 100px;height: 100px;"
              :src="getUrl(row)"
            ></el-image>
            <video
              v-if="getMediaType(row) == 'video'"
              :src="getUrl(row)"
              style="width: 100%"
            ></video>
          </div>
        </template>
        <template slot-scope="{ row }" slot="ads">
          <div>
            {{ countAds(row) }}
          </div>
        </template>
        <template slot-scope="{row}" slot="platformList">
          <div style="display: flex;">
            <div style="width: 20px;margin-right: 4px"
                 v-for="(item,index) in platformLogo(row.platformList)"
                 :key="index">
              <img style="width: 100%" :src="item.url" :title="item.name">
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="name">
          <span :class="{ 'hasCreative' : row.creativeId && row.creativeId > 0 }">{{ row.name }}</span>
        </template>
        <template slot-scope="{ row }" slot="spend">
          <span>{{ thousandSeparator(row.spend) }}</span>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" plain
                     size="small"
                     style="width: 70px"
                     :disabled="!(selectionList.length > 0)"
                     @click="handleRelation('relation')">关联
          </el-button>
          <el-button type="success"
                     size="small"
                     plain
                     style="width: 70px"
                     :disabled="!(selectionList.length > 0)"
                     @click="handlePut('put')">入库
          </el-button>
          <el-button type="danger"
                     size="small"
                     plain
                     style="width: 70px"
                     :disabled="!(selectionList.length > 0)"
                     @click="handleRemove">移除
          </el-button>
        </template>

        <template slot-scope="{row}" slot="menu">
          <el-tooltip content="查看" placement="top">
            <el-button size="small" icon="el-icon-view" type="text" @click="handleViewCheck(row)"></el-button>
          </el-tooltip>
          <span style="padding-left: 10px;"></span>
          <el-tooltip content="关联" placement="top">
            <el-button icon="el-icon-link" type="text" @click="handleRelation(row)"></el-button>
          </el-tooltip>
          <el-tooltip content="入库" placement="top">
            <el-button icon="el-icon-folder-add" type="text" @click="handlePut(row)"></el-button>
          </el-tooltip>
          <el-popover
            :ref="'popover_'+row.assetId"
            placement="left"
            width="300"
            trigger="click">
            <el-tooltip slot="reference" content="移除" placement="top" style="margin-left: 10px">
              <el-button icon="el-icon-delete" type="text"></el-button>
            </el-tooltip>
            <div>
              <div style="text-align: center">
                <i class="el-icon-warning" style="color:#ff3a30"></i>确认后未知素材将从列表移除且不可恢复，是否继续移除
              </div>
              <div style="display: flex;justify-content: center;margin-top: 10px">
                <el-button size="mini" @click="cancelRemove(row)">取消</el-button>
                <el-button size="mini" type="danger" @click="rowRemove(row)">确认删除</el-button>
              </div>
            </div>
          </el-popover>

        </template>
      </avue-crud>
      <notfound-add-creative :title="title" :drawer-visible="drawerVisible" @close="handleCloseDrawer" :type="drawerType"
                       :check-init="checkInit" :put-init="putInit" :rows-list="rowsList"
      ></notfound-add-creative>

      <notfound-detail :title="title" :drawer-visible="detailVisible" @close="detailVisible = false" :type="drawerType"
                       :check-init="checkInit" :rows-list="rowsList" :updateTimeRange="updateTimeRange">
      </notfound-detail>

      <el-drawer title="素材关联" :visible="relationVisible"
                 :modal-append-to-body="false"
                 :append-to-body="true"
                 :close-on-press-escape="false"
                 :wrapperClosable="false"
                 :before-close="handleRelationClose" size="70%">
        <notfound-relation :notfound-creative-list="relationList"
                           @close="handleRelationClose" ref="notfoundRelation"
                           @handle-put="handlePut"></notfound-relation>
      </el-drawer>
    </basic-container>

    <el-dialog
      title="预览"
      :visible="mediaPreviewDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
      :append-to-body="true"
      style="text-align: center"
    >
      <img
        v-if="mediaPreviewDialog.dialogType === 'image'"
        :style="previewStyle()"
        :src="mediaPreviewDialog.previewUrl"
      />
      <video
        ref="video"
        v-if="mediaPreviewDialog.dialogType === 'video'"
        :src="mediaPreviewDialog.previewUrl"
        :style="previewStyle()"
        controls="controls"
      ></video>
    </el-dialog>

  </div>
</template>

<script>
import beetlesSearch from "@/components/basic-components/beetles-search"
import beetlesTable from "@/components/basic-components/beetles-table"
import notfoundAddCreative from "@/views/creativeReport_bc/notfoundComponents/notfoundAddCreative";
import notfoundDetail from "@/views/creativeReport_bc/notfoundComponents/notfoundDetail";
import notfoundRelation from "@/views/creativeReport_bc/notfoundComponents/notfoundRelation";
import notfoundSearchCreative from "@/views/creativeReport_bc/notfoundComponents/notfoundSearchCreative";
import {getList, removeNotFound} from "@/api/creativeReport/notFoundCreative";
import {getOfferList} from "@/api/business/share";
import {getSysDictList} from "@/api/system/dict";
import {findObject, thousandSeparator,columnTip} from "@/util/util";
import Moment from "moment";
import {getAllUser} from "@/api/user";
import {platformLogo} from "@/util/beetles";
import store from '@/store';
import {createEventHandler} from "@/util/events";
import {getOfferName} from "@/api/business/offer";

export default {
  components: {
    notfoundAddCreative,
    notfoundRelation,
    notfoundDetail,
    notfoundSearchCreative,
    beetlesSearch,
    beetlesTable,
  },
  name: "notfoundCreative",
  data() {
    return {
      oc: store.state.user.oc,
      popoverVisible: false,
      checkInit: {},
      putInit: {},
      query: {
        offerId: null,
        name: null,
        platform: null,
        countryList: null,
        type: '',
      },
      offer: {
        id: null,
        name: null,
      },
      updateTimeRange: [],
      platformList: [],//平台列表
      nationList: [], //地区列表
      originatorList: [],
      offerList: [],//订单列表
      typeList: [
        {label: '图片', value: '0'},
        {label: '视频', value: '1'}
      ],
      selectionList: [],
      data: [],
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      rowsList: [],
      rules: {
        offerId: [
          {required: true, message: '请选择订单', trigger: 'blur'},
        ],
      },
      option: {
        border: true,
        index: true,
        selection: true,
        tip:false,
        menu: true,
        editBtn:false,
        delBtn:false,
        menuLeft: true,
        column: [
          {
            label: "素材",
            prop: "assetUrl",
            width: 120
          },
          {
            label: "名称",
            prop: "name",
            overHidden: true,
            width: 300,
            renderHeader: (h, {column}) => {
              return columnTip(h, column, '从广告后台实际获取到的素材名称')
            },
          },
          {
            label: "assetId",
            prop: "assetId",
            width: 200,
            overHidden: true,
            renderHeader: (h, {column}) => {
              return columnTip(h, column, '来自媒体后台，从广告实际投放情况来看，一个素材可对应多个assetid')
            },
          },
          // {id:"0",value:"图片"},
          // {id:"1",value:"视频"},
          {
            label: '素材类型',
            prop: 'type',
            type: 'select',
            dicData: [
              {label: '图片', value: 0},
              {label: '视频', value: 1}
            ],
            width: 80
          },
          {
            label: "媒体",
            prop: "platformList",
            width: 150,
            renderHeader: (h, {column}) => {
              return columnTip(h, column, '广告/素材实际产生归因数据的平台')
            },
          },
          {
            label: "花费",
            prop: "spend",
            sortable: "custom",
          },
        ],

      },
      // type:"1",
      title: '',
      drawerVisible: false,
      detailVisible: false,
      relationVisible: false,
      relationList: [],
      drawerType: '',
      sortList: [{name: 'spend', orderBy: 'desc'}],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 3600 * 1000 * 24;
        },
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近30天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近90天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
    }
  },
  created() {
    this.init();
    this.drawerPutInit();
    this.updateTimeRange = [Moment().subtract("days", 8).format("yyyy-MM-DD"), Moment().subtract("days", 1).format("yyyy-MM-DD")];

    if (this.oc === true) {
      let self = this;
      this.eventHandler = createEventHandler("offerCenter")
        .addListener((event) => {
          if (event.message === 'offerChanged' && event.offerId && event.offerId !== "") {
            this.query.offerId = event.offerId
            this.offer.id = event.offerId
            getOfferName(event.offerId).then(res => {
              this.offer.name = res.data.data;
            })
            self.submitForm();
          }
        });
      this.updateTimeRange = [Moment().subtract("days", 7).format("yyyy-MM-DD"), Moment().subtract("days", 1).format("yyyy-MM-DD")];
      this.query.offerId = store.state.user.offer
      this.offer.id = store.state.user.offer
      getOfferName(this.offer.id).then(res => {
        this.offer.name = res.data.data;
      })
      this.submitForm();
    } else {
      this.resetValue();
    }

  },
  computed: {},
  methods: {
    getUrl(row) {
      return row.obsUrl || row.assetUrl;
    },
    validateData(rule, value, callback) {
      if (!this.query.name && this.updateTimeRange == null) {
        callback(new Error('素材名称和更新时间需必填一项'));
      } else {
        callback();
      }
    },
    obsStyle(row) {
      return {
        'obs': row.obsUrl != null && row.obsUrl != ''
      }
    },
    //初始化
    init() {
      //获取订单列表
      getOfferList().then(res => {
        this.offerList = res.data.data;
      });
      //获取投放地区和平台类型
      getSysDictList("platforms,nation").then((map) => {
        this.platformList = map['platforms']
        this.nationList = map['nation'];
        let column = findObject(this.option.column, 'countryList', 'prop');
        if (column != null) {
          column.dicData = this.nationList;
        }
        let columnPlatform = findObject(this.option.column, 'platformList', 'prop');
        if (columnPlatform != null) {
          columnPlatform.dicData = this.platformList;
        }
      });
    },
    drawerPutInit() {
      getAllUser({statusList: '1', isAll: false}).then(res => {
        this.originatorList = res.data.data
      });
    },
    resetValue() {
      this.page.currentPage = 1;
      this.type = 0;
      //默认时间
      this.updateTimeRange = null;
      //this.updateTimeRange = [Moment().subtract("days", 8).format("yyyy-MM-DD"), Moment().subtract("days", 1).format("yyyy-MM-DD")];
      // this.updateTimeRange = ['2022-03-01', '2022-03-01'];
    },
    changOffer(value) {
      this.offer = this.offerList.find((item) => {
        return item.id === value;
      });
      this.submitForm();
    },
    /**
     * 搜索
     */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.page.currentPage = 1;
          this.onLoad(this.page)
        } else {
          return false;
        }
      });
    },
    /**
     * 清空搜索栏
     */
    emptyForm() {
      this.$refs.form.resetFields();
      this.resetValue();
      this.submitForm();
    },
    /**
     * 查看
     */
    handleViewCheck(row) {
      this.title = row.name;
      this.detailVisible = true;
      this.rowsList = []
      this.rowsList.push(row)
      this.checkInit = Object.assign({platformList: this.platformList, nationList: this.nationList})
    },
    /**
     * 关联未知素材
     */
    handleRelation(row) {
      if (row === 'relation') {
        this.relationList = this.selectionList
        this.relationVisible = true;
      } else {
        this.relationList.push(row)
        this.relationVisible = true;
      }
      this.title = '素材关联';
      this.$nextTick(() => {
        this.$refs.notfoundRelation.initRelation(this.offer);
      })
      // this.$refs.notfoundRelation.initRelation();
    },
    //关闭关联未知素材弹窗
    handleRelationClose(update) {
      this.relationList = []
      this.relationVisible = false;
      if (update === true) {
        this.detailVisible = false;
        this.onLoad(this.page)
      }
    },
    /**
     * 入库
     */
    handlePut(row) {
      if (row === 'put') {
        this.rowsList = this.selectionList
      } else {
        this.rowsList = []
        this.rowsList.push(row)
      }

      for (let i = 0; i < this.rowsList.length; i++) {
        let ele = this.rowsList[i];
        if (ele.obsUrl == null || ele.obsUrl == '') {
          this.$message({
            type: 'error',
            message: '【' + ele.name + '】的Obs地址为空，不能入库！'
          });
          return;
        }
      }
      this.drawerVisible = true;
      this.title = '未知素材 - 入库';
      this.putInit = Object.assign({offerId: this.query.offerId, originatorList: this.originatorList})
      this.drawerType = 'put'
    },
    /**
     * 移除单个未知素材
     */
    rowRemove(row) {
      let data = [];
      data.push(row)
      removeNotFound(data).then(res => {
        if (res.status === 200) {
          this.$refs['popover_' + row.assetId].doClose();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.onLoad(this.page)
        }
      })
    },
    cancelRemove(row) {
      // this.$message.info('已取消删除')
      this.$refs['popover_' + row.assetId].doClose();
    },

    /**
     * 移除
     */
    handleRemove() {
      this.$confirm('确认后未知素材将从列表移除且不可恢复,是否继续移除', {
        confirmButtonText: '确定移除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = [];
        this.selectionList.map(item => {
          data.push(item)
        })
        removeNotFound(data).then(res => {
          if (res.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.onLoad(this.page)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      if (done) {
        done();
      }
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page);
    },

    async onLoad(page, params = {}) {
      if (!this.query.offerId) return;
      this.loading = true;
      let sortList = this.sortList;
      let queryParam = {...this.query};
      if (this.updateTimeRange && this.updateTimeRange.length > 0) {
        queryParam['beginDate'] = this.updateTimeRange[0]
        queryParam['endDate'] = this.updateTimeRange[1]
      }
      // queryParam.countryList = this.query.countryList.join(',');
      await getList(page.currentPage, page.pageSize,
        Object.assign(params, queryParam,{sortList: JSON.stringify(sortList)})
        ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    thousandSeparator(num) {
      return thousandSeparator(num);
    },
    handleMediaPreview(row) {
      let type = this.getMediaType(row);
      if (type == null || type == '') {
        return;
      }
      this.mediaPreviewDialog.previewUrl = this.getUrl(row);
      this.mediaPreviewDialog.dialogType = type;
      this.mediaPreviewDialog.dialogVisible = true;
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    /**
     * 素材类型
     */
    getMediaType(row) {
      const url = this.getUrl(row);
      if (row.type == 0) {
        return 'image';
      } else if (row.type == 1) {
        return 'video';
      } else if (url != null && url != '') {
        if (url.includes('image')) {
          return 'image';
        }
        if (url.includes('videos')) {
          return 'video';
        }
      }
      return '';
    },
    /**
     * 平台
     */
    platformLogo(val) {
      return platformLogo(val)
    },
    /**
     * 关闭弹窗
     */
    handleCloseDrawer(update) {
      this.checkInit = {};
      this.putInit = {};
      if (this.drawerType === 'put') {
        // this.onLoad(this.page)
      }
      this.drawerVisible = false;
      if (update === true) {
        this.relationVisible = false;
        this.onLoad(this.page)
      }
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-drawer.rtl {
  overflow: scroll !important;
}

.hasCreative {
  color: #34A9FF
}

.obs {
  border: 2px solid #00a2ff;
}
</style>
